14. Exclusions and Transitive Dependencies
Exclusions and Transitive Dependencies
ND079 JPND C3 L2 A12 Exclusions And Transitive Dependencies V3
Transitive Dependencies
A **transitive dependency **is a resource required by one of the dependencies included in your project. For example, if I declare a dependency on the testing utility Mockito, its dependency JUnit will become a transitive dependency of my project.
If your project has multiple transitive dependencies, the nearest definition will win. That means the first one declared in your pom if the dependencies are all at the same depth. If your transitive dependencies are nested more deeply, the version with the shallowest depth will be chosen. In the below example, JUnit 5.7 will be chosen.
Resolving Transitive Dependencies
To resolve transitive dependency confusion, there are two options:
- Directly include the dependency in question. The version you use will become the nearest definition and be selected by Maven.
- Use the
<exclusion>
tag to specifically exclude versions you do not wish to use.
For example, this code will exclude the version of JUnit from Mockito, resulting in an included version of 5.7 being selected.
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito</artifactId>
<exclusions>
<exclusion>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency